package com.example.campusforumapi.controller;

import com.example.campusforumapi.entity.Department;
import com.example.campusforumapi.entity.User;
import com.example.campusforumapi.service.DepartmentService;
import com.example.campusforumapi.util.PageResult;
import com.example.campusforumapi.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/departments")
public class DepartmentController extends BaseController{
    @Autowired
    private DepartmentService departmentService;

    /*
     * 按条件  分页查询
     * */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize
            ){

        //        查询并封装分页结果集
        PageResult departmentPage = departmentService.getDepartmentPage(page,pageSize);

        return Result.success(departmentPage);
    }

    //    删除一条记录
    @DeleteMapping("/delete/{ids}")
    public Result delete(@PathVariable List<Integer> ids){
        departmentService.delDepartment(ids);
        return Result.success();
    }

    //    新增一条记录
    @PostMapping ("/insert")
    public Result insert(@RequestBody Department department){
        if(StringUtils.isEmpty(department.getDepartmentName()) || StringUtils.isEmpty(department.getDepartmentId())){
            return Result.error("院系名称名及院系id不能为空");
        }
        else if (departmentService.findsamedepartmentName(department.getDepartmentName())>=1) {
            return Result.error("院系名称已存在");
        }
        else if(departmentService.findsameDepartmentId(department.getDepartmentId())>=1){
            return Result.error("该院系编号已存在");
        }
        else if(departmentService.insertDepartment(department) > 0){
            return Result.success("插入成功");
        }else{
            return Result.error("插入异常");
        }

    }

    //    修改一条记录
    @PutMapping("/update")
    public Result update(@RequestBody Department department){
        if(departmentService.updDepartment(department) > 0){
            return Result.success("修改成功");
        }else{
            return Result.error("修改失败，该院系不存在");
        }

    }


}
